package com.vehiclemanagement.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vehiclemanagement.entity.FuelCard;
import com.vehiclemanagement.entity.FuelRefill;
import com.vehiclemanagement.entity.Vehicle;
import com.vehiclemanagement.mapper.FuelCardMapper;
import com.vehiclemanagement.mapper.FuelRefillMapper;
import com.vehiclemanagement.mapper.VehicleMapper;
import com.vehiclemanagement.service.FuelRefillService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.Year;
import java.util.List;
import java.util.Map;

/**
 * 加油记录服务实现类
 */
@Service
public class FuelRefillServiceImpl extends ServiceImpl<FuelRefillMapper, FuelRefill> implements FuelRefillService {

    @Autowired
    private FuelRefillMapper fuelRefillMapper;
    
    @Autowired
    private FuelCardMapper fuelCardMapper;
    
    @Autowired
    private VehicleMapper vehicleMapper;

    @Override
    public IPage<FuelRefill> pageRefills(Integer current, Integer size, String searchTerm, 
                                       Long vehicleId, Long driverId, Long fuelCardId, Integer fuelType,
                                       LocalDateTime startTime, LocalDateTime endTime) {
        // 创建分页对象
        Page<FuelRefill> page = new Page<>(current, size);
        
        // 创建自定义SQL条件
        String whereSql = " f.del_flag = 0 ";
        
        // 添加搜索条件
        if (StringUtils.isNotBlank(searchTerm)) {
            whereSql += " AND (v.plate_number LIKE '%" + searchTerm + "%' OR d.name LIKE '%" + searchTerm + "%' " +
                    "OR fc.card_number LIKE '%" + searchTerm + "%') ";
        }
        
        // 添加车辆ID查询条件
        if (vehicleId != null) {
            whereSql += " AND f.vehicle_id = " + vehicleId;
        }
        
        // 添加驾驶员ID查询条件
        if (driverId != null) {
            whereSql += " AND f.driver_id = " + driverId;
        }
        
        // 添加加油卡ID查询条件
        if (fuelCardId != null) {
            whereSql += " AND f.fuel_card_id = " + fuelCardId;
        }
        
        // 添加油品类型查询条件
        if (fuelType != null) {
            whereSql += " AND f.fuel_type = " + fuelType;
        }
        
        // 添加时间范围查询条件
        if (startTime != null) {
            whereSql += " AND f.refill_time >= '" + startTime + "'";
        }
        
        if (endTime != null) {
            whereSql += " AND f.refill_time <= '" + endTime + "'";
        }
        
        // 添加排序
        whereSql += " ORDER BY f.refill_time DESC";
        
        System.out.println("执行查询SQL条件: " + whereSql);
        
        // 执行查询
        return fuelRefillMapper.selectPageWithInfo(page, whereSql);
    }

    @Override
    public FuelRefill getRefillById(Long id) {
        return fuelRefillMapper.selectById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addRefill(FuelRefill refill) {
        System.out.println("服务层开始添加加油记录: " + refill);
        
        try {
            // 设置默认值
            if (refill.getRefillTime() == null) {
                refill.setRefillTime(LocalDateTime.now());
            }
            if (refill.getCreateTime() == null) {
                refill.setCreateTime(LocalDateTime.now());
            }
            if (refill.getUpdateTime() == null) {
                refill.setUpdateTime(LocalDateTime.now());
            }
            if (refill.getDelFlag() == null) {
                refill.setDelFlag(0);
            }
            
            // 如果总金额为空，则根据单价和数量计算
            if (refill.getTotalPrice() == null && refill.getUnitPrice() != null && refill.getFuelAmount() != null) {
                refill.setTotalPrice(refill.getUnitPrice().multiply(refill.getFuelAmount()));
            }
            
            // 先插入加油记录
            int result = fuelRefillMapper.insert(refill);
            
            if (result > 0) {
                // 更新加油卡余额
                if (refill.getFuelCardId() != null && refill.getTotalPrice() != null) {
                    FuelCard fuelCard = fuelCardMapper.selectById(refill.getFuelCardId());
                    if (fuelCard != null) {
                        // 扣减余额
                        BigDecimal newBalance = fuelCard.getBalance().subtract(refill.getTotalPrice());
                        // 余额不能为负
                        if (newBalance.compareTo(BigDecimal.ZERO) < 0) {
                            newBalance = BigDecimal.ZERO;
                        }
                        fuelCard.setBalance(newBalance);
                        fuelCard.setUpdateTime(LocalDateTime.now());
                        
                        fuelCardMapper.updateById(fuelCard);
                        System.out.println("更新加油卡余额成功，卡号: " + fuelCard.getCardNumber() + ", 新余额: " + newBalance);
                    }
                }
                
                // 更新车辆当前里程
                if (refill.getVehicleId() != null && refill.getCurrentMileage() != null) {
                    Vehicle vehicle = vehicleMapper.selectById(refill.getVehicleId());
                    if (vehicle != null && (vehicle.getCurrentMileage() == null || vehicle.getCurrentMileage() < refill.getCurrentMileage())) {
                        vehicle.setCurrentMileage(refill.getCurrentMileage());
                        vehicle.setUpdateTime(LocalDateTime.now());
                        vehicleMapper.updateById(vehicle);
                        System.out.println("更新车辆当前里程成功，车牌号: " + vehicle.getPlateNumber() + ", 新里程: " + refill.getCurrentMileage());
                    }
                }
            }
            
            System.out.println("插入结果: " + result + ", 生成的ID: " + refill.getId());
            
            return result > 0;
        } catch (Exception e) {
            System.err.println("添加加油记录发生异常: " + e.getMessage());
            e.printStackTrace();
            throw e; // 抛出异常以触发事务回滚
        }
    }

    @Override
    public boolean updateRefill(FuelRefill refill) {
        // 更新时间
        refill.setUpdateTime(LocalDateTime.now());
        
        return fuelRefillMapper.updateById(refill) > 0;
    }

    @Override
    public boolean deleteRefill(Long id) {
        // 使用物理删除
        System.out.println("执行物理删除加油记录，ID: " + id);
        
        try {
            // 直接物理删除记录
            int result = fuelRefillMapper.deletePhysically(id);
            System.out.println("物理删除结果: " + result);
            return result > 0;
        } catch (Exception e) {
            System.err.println("删除加油记录时出错: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public BigDecimal sumFuelAmountByVehicleId(Long vehicleId) {
        return fuelRefillMapper.sumFuelAmountByVehicleId(vehicleId);
    }

    @Override
    public BigDecimal sumTotalPriceByVehicleId(Long vehicleId) {
        return fuelRefillMapper.sumTotalPriceByVehicleId(vehicleId);
    }

    @Override
    public List<Map<String, Object>> statisticsByMonth(Integer year) {
        if (year == null) {
            year = Year.now().getValue();
        }
        
        LocalDateTime startTime = LocalDateTime.of(year, 1, 1, 0, 0, 0);
        LocalDateTime endTime = LocalDateTime.of(year, 12, 31, 23, 59, 59);
        
        return fuelRefillMapper.statisticsByMonth(startTime, endTime);
    }
}